
/**
 * 封装微信小游戏接品API
 * 如果报错在项目根目录下执行
 * npm install @types/wechat-miniprogram
 * 生成官方 api.d.ts
 */

import * as cc from 'cc';
import { WECHAT } from 'cc/env';
// import 'miniprogram-api-typings';
import { GameUtils } from '../../game/utils/GameUtils';
import { Loger } from '../loger/Loger';
import { RandomUtils } from '../utils/RandomUtils';

export enum AdStatus {
    FAIL = 0,
    SUCCESS = 1,
    ERROR = 2
}


export enum CustomAdType{
    //0:单个，1：横向多个，2：竖向多个，3：矩阵
    One = 0,
    Heng = 1,
    Shu = 2,
    More = 3
}
//广告的位置
export enum BannerPlacement {
    TOP,
    MIDDLE,
    BOTTOM,
}

export interface WxUserInfo {
    /** 用户头像图片的 URL。URL 最后一个数值代表正方形头像大小（有 0、46、64、96、132 数值可选，0 代表 640x640 的正方形头像，46 表示 46x46 的正方形头像，剩余数值以此类推。默认132），用户没有头像时该项为空。若用户更换头像，原有头像 URL 将失效。 */
    avatarUrl?: string
    /** 用户所在城市。不再返回，参考 [相关公告](https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801) */
    city?: string
    /** 用户所在国家。不再返回，参考 [相关公告](https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801) */
    country?: string
    /** 用户性别。不再返回，参考 [相关公告](https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801)
     *
     * 可选值：
     * - 0: 未知;
     * - 1: 男性;
     * - 2: 女性; */
    gender?: 0 | 1 | 2
    /** 显示 country，province，city 所用的语言。强制返回 “zh_CN”，参考 [相关公告](https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801)
     *
     * 可选值：
     * - 'en': 英文;
     * - 'zh_CN': 简体中文;
     * - 'zh_TW': 繁体中文; */
    language?: 'en' | 'zh_CN' | 'zh_TW'
    /** 用户昵称 */
    nickName: string
    /** 用户所在省份。不再返回，参考 [相关公告](https://developers.weixin.qq.com/community/develop/doc/00028edbe3c58081e7cc834705b801) */
    province?: string
}


/**微信开放数据结构 */
export interface WxUserCloudStorageData {
    KVDataList: { key: string, value: string }[],
    success: (res) => void,
    fail: (res) => void
}

export class WxUtils {

    static _instance: WxUtils;

    public static getInstance() {
        if (this._instance) {
            return this._instance;
        }
        this._instance = new WxUtils();
        return this._instance;
    }


    public static isWx() {
        return cc.sys.platform == cc.sys.Platform.WECHAT_GAME;
    }

    /**
     * @desc 微信登录
     * @returns code
     */
    public static login(): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            if (!WxUtils.isWx()) {
                resolve("");
            }
            wx.login({
                success(res) {
                    Loger.log("-->success result-->>", res);
                    if (res.code) {
                        //发起网络请求
                        resolve(res.code);
                    } else {
                        Loger.log('登录失败！' + res.errMsg)
                        reject(res);
                    }
                }
            })
        })
    }

    public static getUserInfo(code: string): Promise<WxUserInfo> {
        return new Promise<WxUserInfo>((resolve, reject) => {
            wx.getSetting({
                success(res) {
                    Loger.log("用户的授权列表")
                    Loger.log(res.authSetting)
                    if (res.authSetting["scope.userInfo"]) {
                        Loger.log("已经获取到scope.userInfo")
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if(WxUtils.compareGameVersion(version,'2.33.0')>= 0){
                            wx["requirePrivacyAuthorize"]({
                                success: res=>{
                                    console.log("同意了2")
                                    wx.getUserInfo({
                                        lang: "zh_CN",
                                        withCredentials: true,
                                        success: (result) => {
                                            Loger.log("-->getUserInfo success result-->>", result);
                                            resolve(result.userInfo)
                                        },
                                        fail: (result) => {
                                            Loger.log("-->>getUserInfo fail result-->>", result);
                                            reject(result);
                                        }
                                    })
                                },
                                fail: ()=>{
                                    console.log("拒绝了2")
                                    GameUtils.showTip("登录需要你的昵称,请打开");
                                    wx.openSetting({
                                        success (res) {
                                          console.log(res.authSetting)
                                          // res.authSetting = {
                                          //   "scope.userInfo": true,
                                          //   "scope.userLocation": true
                                          // }
                                        }
                                      })
                                },
                                complete:()=>{
                                    console.log("完成了2")
                                },
                            });
                        }else{
                            wx.getUserInfo({
                                lang: "zh_CN",
                                withCredentials: true,
                                success: (result) => {
                                    Loger.log("-->getUserInfo success result-->>", result);
                                    resolve(result.userInfo)
                                },
                                fail: (result) => {
                                    Loger.log("-->>getUserInfo fail result-->>", result);
                                    reject(result);
                                }
                            })
                        }
                        
                        
                    } else {
                        console.log("getUserProfile调用")
                        Loger.log("还未获取到scope.userInfo")
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if(WxUtils.compareGameVersion(version,'2.33.0')>= 0){
                            wx["requirePrivacyAuthorize"]({
                                success: res => {
                                    console.log("同意了")
                                    // 非标准API的方式处理用户个人信息
                                    wx.getUserProfile({
                                        desc: '用于登录游戏', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                                        success: (result) => {
                                            Loger.log("-->getUserProfile success result-->>", result);
                                            resolve(result.userInfo)
                                        },
                                        fail: (result) => {
                                            Loger.log("-->getUserProfile fail result-->>", result);
                                            reject(result);
                                        }
                                    })
                                },
                                fail: () => {
                                    console.log("拒绝了")
                                    GameUtils.showTip("登录需要你的昵称,请打开");
                                    wx.openSetting({
                                        success (res) {
                                          console.log(res.authSetting)
                                          // res.authSetting = {
                                          //   "scope.userInfo": true,
                                          //   "scope.userLocation": true
                                          // }
                                        }
                                      })
                                },
                                complete:()=>{
                                    console.log("完成了")
                                },
                            })
                        }else{
                            wx.getUserProfile({
                                desc: '用于登录游戏', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                                success: (result) => {
                                    Loger.log("-->getUserProfile success result-->>", result);
                                    resolve(result.userInfo)
                                },
                                fail: (result) => {
                                    Loger.log("-->getUserProfile fail result-->>", result);
                                    reject(result);
                                }
                            })
                        }
                        
                        
                    }

                    if (res.authSetting["scope.WxFriendInteraction"]) {
                        Loger.log("已经授权使用你的微信朋友信息")
                    } else {
                        Loger.log("还未授权使用你的微信朋友信息")
                    }

                }

            })

        })

    }

    /**上报分数 */
    public static setUserCloudStorage(data: WxUserCloudStorageData) {
        if (!WxUtils.isWx()) {
            return;
        }
        Loger.log("上报分数", data)
        wx["setUserCloudStorage"](data)
    }

    public static onMessage(callback: (data) => void) {
        if (!WxUtils.isWx()) {
            callback && callback(null);
            return;
        }
        wx["onMessage"](data => {
            cc.log("接收主域发来消息：", data);
            callback && callback(data);
        });
    }

    public static postMessage(data: any) {
        if (!WxUtils.isWx()) {
            return;
        }
        Loger.log("发送消息到子域", data)
        wx["postMessage"](data);
    }

    /**
     * 
     * @returns 获取微信右上角菜单距离顶部的高度
     */
    public static getMenuButtonRect(): number {
        if (!WxUtils.isWx()) {
            return;
        }
        const res = wx.getMenuButtonBoundingClientRect();
        Loger.log(res.width)
        Loger.log('height:', res.height)//胶囊高度
        Loger.log('top:', res.top) //胶囊距离顶部
        Loger.log('right:', res.right)
        Loger.log(res.bottom)
        Loger.log(res.left)
        Loger.log("高度：", (res.top + res.height))
        return res.top + res.height;
    }

    /**
     * 用户被动分享设置，用户自己右上角点3个点分享
     * @returns 
     */
    public static passiveShareSet() {
        Loger.log("用户被动分享设置")
        if (!WxUtils.isWx()) {
            return;
        }
        //设置显示分享朋友和朋友圈菜单
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        //右上角点击3个点,分享给好友的设置 用户点击了“转发”按钮
        wx["onShareAppMessage"](() => {
            return {
                title: '这个游戏贼解压,还等什么,快来玩吧！',
                imageUrl: 'https://mmocgame.qpic.cn/wechatgame/bSAKPPBBQFVfXsHAosdFCYXoOo19xLcFlz23icoLXLiaayKJXqTiayyCYjx2ZC5CrHY/0', // 图片 URL
                query: 'shareid=100' //分享参数，别人打开的时候能取到
            }
        })
        //分享到朋友圈的设置，设置分享图片、标题，若不设置，则会以小游戏名称作为分享标题，以小游戏 logo 作为分享图片。
        wx["onShareTimeline"](() => {
            return {
                title: '我在榜一等你，不见不散',
                imageUrl: 'https://mmocgame.qpic.cn/wechatgame/bSAKPPBBQFVfXsHAosdFCYXoOo19xLcFlz23icoLXLiaayKJXqTiayyCYjx2ZC5CrHY/0', // 图片 URL
                query: 'shareid=200' //分享参数，别人打开的时候能取到
            }
        })

        wx["onUserCaptureScreen"](() => {
            // 用户截屏了
            wx["showShareImageMenu"]({
                path: ""
            })
        })
        //监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件
        wx["onHide"](() => {
            Loger.log("onHide")
        })
        //监听小游戏回到前台的事件
        wx["onShow"]((res) => {
            Loger.log("onShow")
            if (WxUtils.isFromShare) {
                let curTime = new Date().getTime();
                if (curTime - WxUtils.closeTime > 3000) {
                    Loger.log("分享不给回调是否成功，时间大于3秒算成功给道具")
                    WxUtils.shareCall && WxUtils.shareCall(true);
                    
                } else {
                    Loger.log("时间小于3秒算失败")
                    // wx["showToast"]({
                    //     title: '亲,分享失败',
                    //     icon: 'error',
                    //     duration: 1000
                    //   })
                    WxUtils.shareCall && WxUtils.shareCall(false);
                }
                WxUtils.isFromShare = false;
            }

        })
    }
    public static closeTime = new Date().getTime();
    public static isFromShare: boolean = false;
    public static shareCall: Function = null;
    /**
     * 用户主动点击分享按钮
     * @param call 
     */
    public static shareToFriend(call: Function) {
        if (!WxUtils.isWx()) {
            return;
        }
        WxUtils.shareCall = call;
        WxUtils.closeTime = new Date().getTime();
        WxUtils.isFromShare = true;
        let strArr = ["带薪上厕所的时候玩这个腿都玩嘛了", "你能坚持几秒，跑多远？", "这个游戏贼解压,还等什么,快来吧！", "我很寂寞,快来陪我玩吧", "据说玩这个游戏能减肥,不信你试试?", "据说这个游戏太好玩,做梦都能笑醒,不信你试试?", "据说这个能陪玩,陪聊,还陪睡,不信你试试?", "这个游戏让我找到了初恋的感觉,你也来找找", "我待你如初恋,你虐我千万遍,可我还是想被你虐"];
        let idx = RandomUtils.rangeInt(strArr.length - 1)
        let txt = strArr[idx];

        let url = 'https://mmocgame.qpic.cn/wechatgame/bSAKPPBBQFVfXsHAosdFCYXoOo19xLcFlz23icoLXLiaayKJXqTiayyCYjx2ZC5CrHY/0'
        wx["shareAppMessage"]({
            title: txt,
            imageUrl: url
        })
        //call && call()

    }



    public static createWxGameHub(pos_x, pos_y) {
        if (!WxUtils.isWx()) {
            return;
        }
        let windowSize = cc.view.getVisibleSize();
        let leftRatio = pos_x / windowSize.width;
        let topRatio = pos_y / windowSize.height;

        const info = wx.getSystemInfoSync();//立即获取系统信息
        const w: number = info.screenWidth;//屏幕宽
        const h: number = info.screenHeight;//屏幕高
        Loger.log("屏幕宽:" + w)
        Loger.log("屏幕高:" + h)
        
        let leftPos = info.windowWidth * leftRatio;
        let topPos = info.windowHeight * (topRatio);
        Loger.log("posx,posy,leftRatio,topRatio,leftPos,topPos", pos_x, pos_y, leftRatio, topRatio, leftPos, topPos)
        let gameClubButton = wx["createGameClubButton"]({
            icon: 'light',//green dark white light
            style: {
                left: leftPos - 21,//5,
                top: topPos - 20 + 57,//150,
                width: 40,
                height: 40,
                backgroundColor: '#00000000',//最后两位为透明度
                // color: '#ffffff',
            }
        })
        return gameClubButton;
    }



    idBannerAD:string = 'adunit-15ee590b19e8cdf1'//banner广告位id
    idChaPingAD:string = 'adunit-3b2feacea7a2d140'//插屏广告位id
    idJiLiShiPinAD:string = 'adunit-784e352c17edaa12'//激励视频广告位id
    
    nativeAd:any = { // 原生模板广告
        dange_id: 'adunit-e969b6feb8fd2784',
        juzhen_id:'adunit-bba06f21db8d48e1', //九宫格
        heng_id:'adunit-10d9e407553ae296',  //横向4个 
        zong_R_id:"adunit-c64679eed26952d7",  //纵向2个 右
        zong_L_id:"adunit-9b0938bb954953ef",  //纵向2个 左
    }
    testAd: boolean = false;
    rewardVideo2: any = null;
    ad_Custom_DanGe = null              //单个
    ad_Custom_HengXiang = null          //横向
    ad_Custom_ShuXiang_R = null         //竖向   靠右边
    ad_Custom_ShuXiang_L = null 
    ad_Custom_JuZhen = null             //矩阵   
    showRewardVideo(callback?: Function) {
        if (this.testAd) {
            callback(AdStatus.SUCCESS);
            return;
        }
        let my = this;
        let id = this.idJiLiShiPinAD
        if (my.rewardVideo2 != null) {
            my.rewardVideo2.offClose(fun);
        }
        let rewardedVideoAd = wx["createRewardedVideoAd"]({
            adUnitId: id,
        });
        my.rewardVideo2 = rewardedVideoAd;
        rewardedVideoAd.load().then(() => {
            wx["showToast"]({
                title: "加载中，请稍后",
                icon: 'success',//图标，支持"success"、"loading" 
                duration: 1500,//提示的延迟时间，单位毫秒，默认：1500 
                mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false 
                success: function () { },
                fail: function () { },
                complete: function () { }
            })
            Loger.log('激励视频 广告加载成功');
            rewardedVideoAd.show();
        });
        rewardedVideoAd.onError(err => {
            Loger.log('激励视频 广告显示失败', err);
            wx["showToast"]({
                title: "请稍后再试",
                icon: 'error',//图标，支持"success"、"loading" 
                duration: 1500,//提示的延迟时间，单位毫秒，默认：1500 
                mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false 
                success: function () { },
                fail: function () { },
                complete: function () { }

            })
            callback(AdStatus.ERROR);
        })
        var fun = (res) => {
            if (res && res.isEnded) {
                Loger.log('res:  ', res);
                rewardedVideoAd.offClose(fun);
                callback(AdStatus.SUCCESS);
                // const modelPlayer = ModelPlayer.getInstance() as ModelPlayer;
                // modelPlayer.requestPlayVideoAd().then(()=>{
                //     callback(AdStatus.SUCCESS);
                // }).catch(()=>{
                //     callback(AdStatus.SUCCESS);
                // })
            } else {
                Loger.log('播放中途退出');
                callback(AdStatus.FAIL);
            }
        }
        rewardedVideoAd.onClose(fun);
    }


    showInterstitialAd(delay = 0) {
        if (!WECHAT) {
            return;
        }
        let id = this.idChaPingAD;
        let interstitialAd = wx["createInterstitialAd"]({
            adUnitId: id,
        });
        if (interstitialAd) {
            interstitialAd.load().then(() => {
                Loger.log('插屏 广告加载成功');
            });
            interstitialAd.onClose(res => {
                Loger.log('关闭插屏广告', res);
            });
            interstitialAd.onError(err => {
                Loger.log('err:插屏广告加载失败', err);
            });

            setTimeout(() => {
                interstitialAd.show().catch((err) => {
                    Loger.log('插屏广告展示失败', err);
                });
            }, delay * 1000);
        }
    }


    banner: any = null;
    /**隐藏banner */
    hideBanner() {
        if (!WxUtils.isWx()) {
            return;
        }
        if (this.banner != null) {
            this.banner.hide();
            //this.banner = null;
        }
    }
    showBanner(placement: BannerPlacement = BannerPlacement.BOTTOM) {
        if (this.banner != null) {
            this.banner.show();
        }
        
    }
    /**显示banner */
    loadBanner(placement: BannerPlacement = BannerPlacement.BOTTOM) {
        if (!WECHAT) {
            return;
        }
        if (this.banner != null) {
            //this.banner.show();
            //this.banner = null;
            return;
        }
        let id = this.idBannerAD;
        //let winSize = wx.getSystemInfoSync();
        // let bannerAd = wx["createBannerAd"]({
        //     adUnitId: id,
        //     adIntervals: 30,
        //     style: {
        //         left: 0,
        //         top: 500,
        //         width: 300,
        //     }

        // })
        // let left;
        // if (style == 1) {
        //     left = winSize.windowWidth - bannerAd.style.realWidth;
        // }
        // else if (style == 2) {
        //     left = winSize.windowWidth / 2 - bannerAd.style.realWidth / 2;
        // }
        // else {
        //     left = 0;
        // }
        // bannerAd.onResize(res => {
        //     bannerAd.style.top = winSize.windowHeight - bannerAd.style.realHeight;
        //     bannerAd.style.left = left;
        // })
        const {
            windowWidth,
            windowHeight
        } = wx.getSystemInfoSync();
        //创建 Banner
        let bannerAd = wx["createBannerAd"]({
            adUnitId: id,
            style: {
                left: 0,
                top: 0,
                width: windowWidth
            }
        });
        //         //调整位置
        bannerAd.onResize((size) => {
            switch (placement) {
                case BannerPlacement.TOP:
                    bannerAd.style.top = 0
                    break;
                case BannerPlacement.MIDDLE:
                    bannerAd.style.top = (windowHeight - size.height) / 2;
                    break;
                default:
                    bannerAd.style.top = windowHeight - size.height;
            }
            bannerAd.style.left = (windowWidth - size.width) / 2;

        });
        bannerAd.onLoad(() => {
            Loger.log('banner 广告加载成功');
            this.banner = bannerAd;
        })
        bannerAd.onError(err => {
            Loger.log('banner 广告加载错误', err);
        })
        
    }

    /**
         * 版本号比较
         * @param v1 
         * @param v2 
         * @returns 
         */
   static  compareGameVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }
    


    /**
     * 震动
     */
    vibrateShort() {
        if (!WxUtils.isWx()) {
            return;
        }
        if (wx) {
            wx.vibrateShort({
                type: 'medium'
            });
        }

    }

    /**
     * 跳转到其他小游戏
     * @param appid 小游戏id
     */
    jump(appid): void {
        if (!WxUtils.isWx()) {
            return;
        }
        if (wx) {
            wx.navigateToMiniProgram({
                appId: appid,
                path: '',
                extraData: null,
                envVersion: 'release',
                success(res) {
                    Loger.log('跳转成功');
                }
            })
        }
    }

    getNativeAd(type){
        Loger.log("this.nativeAd="+this.nativeAd)
        let id = ''
        if(type == CustomAdType.More){
            id = this.nativeAd.juzhen_id
        }else if(type == CustomAdType.Heng){
            id = this.nativeAd.heng_id
        }else if(type == CustomAdType.One){
            id = this.nativeAd.dange_id
        }
        return id
    }

    /**
     * 创建原生广告模板
     * @param {0:单个,1:横向多个,2:竖向多个,3:矩阵} type 
     */
    createCustomAd(type){
        if (!WxUtils.isWx()) {
            return;
        }
        if(wx){//微信
            Loger.log('创建原生广告type=', type)
            let inifo = wx.getSystemInfoSync()
            if(WxUtils.compareGameVersion( inifo.SDKVersion ,'2.11.1')>= 0){
                if(type == CustomAdType.One){ //单个
                    //常规样式默认画布为 60×104 像素
                    //卡片样式默认画布为 68×106 像素
                    let adWidth = 60;
                    let adHeight = 104;
                    if(!this.ad_Custom_DanGe){
                        this.ad_Custom_DanGe = wx["createCustomAd"]({
                            adUnitId: this.getNativeAd(type),
                            adIntervals:35,
                            style: {
                                left: 0,//(inifo.screenWidth - adWidth)/2 ,
                                top: inifo.screenHeight - adHeight - 300,
                                fixed:false
                            }
                        })
                        this.ad_Custom_DanGe.onLoad((res)=>{
                            Loger.log('单个原生广告加载', res)
                            if(this.ad_Custom_DanGe && !this.blnHidenOne){
                                this.ad_Custom_DanGe.show();
                            }
                        })
                        this.ad_Custom_DanGe.onError((res)=>{
                            Loger.log('单个原生广告报错', res)
                        })
                        this.ad_Custom_DanGe.onHide((res)=>{
                            Loger.log('单个原生监听关闭')
                        })
                    }
                    
                }else if(type == CustomAdType.Heng){ //横向 顶部 水平布局默认画布为 360×106 像素
                    let adWidth = 360;
                    let adHeight = 110;
                    let id = this.getNativeAd(type)
                    if(!this.ad_Custom_HengXiang){
                        this.ad_Custom_HengXiang = wx["createCustomAd"]({
                            adUnitId: id,
                            adIntervals:35,
                            style: {
                                left: (inifo.screenWidth - adWidth)/2 + 65,
                                top: inifo.screenHeight - adHeight - 150,
                                fixed:false
                            }
                        })
                        this.ad_Custom_HengXiang.onLoad((res)=>{
                            Loger.log('横向原生广告加载', res)
                        })
                        this.ad_Custom_HengXiang.onError((res)=>{
                            Loger.log('横向原生广告报错', res)
                        })
                        this.ad_Custom_HengXiang.onHide((res)=>{
                            Loger.log('横向原生监听关闭')
                        })
                    }
                    
                }else if(type == CustomAdType.Shu){  //竖向 左右 垂直布局默认画布为 72×410 像素
                    let adWidth = 72 
                    let adHeight = 410
                    let id_r = this.nativeAd.zong_R_id
                    Loger.log("inifo.screenHeight="+inifo.screenHeight+" top:"+(inifo.screenHeight - adHeight));
                    if(!this.ad_Custom_ShuXiang_R){
                        this.ad_Custom_ShuXiang_R = wx["createCustomAd"]({
                            adUnitId: id_r,
                            adIntervals:35,
                            style: {
                                left: (inifo.screenWidth - adWidth ) + 15,
                                top: 200,//inifo.screenHeight - adHeight,
                                fixed:false
                            }
                        })
    
                        this.ad_Custom_ShuXiang_R.onLoad((res)=>{
                            Loger.log('竖向R原生广告加载', res)
                        })
                        this.ad_Custom_ShuXiang_R.onError((res)=>{
                            Loger.log('竖向R原生广告报错', res)
                        })
                        this.ad_Custom_ShuXiang_R.onHide((res)=>{
                            Loger.log('竖向R原生监听关闭')
                        })
                    }
                    

                    let id_L = this.nativeAd.zong_L_id;
                    if(!this.ad_Custom_ShuXiang_L){
                        this.ad_Custom_ShuXiang_L = wx["createCustomAd"]({
                            adUnitId: id_L,
                            adIntervals:35,
                            style: {
                                left: 0,
                                top: 200,//inifo.screenHeight - adHeight,
                                fixed:false
                            }
                        })
                        this.ad_Custom_ShuXiang_L.onLoad((res)=>{
                            Loger.log('竖向L原生广告加载', res)
                        })
                        this.ad_Custom_ShuXiang_L.onError((res)=>{
                            Loger.log('竖向L原生广告报错', res)
                        })
                        this.ad_Custom_ShuXiang_L.onHide((res)=>{
                            Loger.log('竖向L原生监听关闭')
                        })
                    }
                    
                    
                }else if(type == CustomAdType.More){ //矩阵
                    // 2×5 布局默认画布为 360×188 像素
                    // 5×5 布局默认画布为 360×352 像素  
                    let adWidth = 360;
                    let adHeight = 500;
                    let id = this.getNativeAd(type)
                    this.ad_Custom_JuZhen = wx["createCustomAd"]({
                        adUnitId: id,
                        adIntervals:35,
                        style: {
                            left: (inifo.screenWidth - adWidth)/2,
                            top: (inifo.screenHeight - adHeight)/2,
                            fixed:false
                        }
                    })
                    this.ad_Custom_JuZhen.onLoad((res)=>{
                        Loger.log('矩阵原生广告加载', res)
                        
                    })
                    this.ad_Custom_JuZhen.onError((res)=>{
                        Loger.log('矩阵原生广告报错', res)
                    })
                    this.ad_Custom_JuZhen.onHide((res)=>{
                        Loger.log('矩阵原生监听关闭')
                    })
                }
            }
        }
    }

    /**
     * 展示 
     * @param {*} ad 
     */
    showCustomAd(type){
        if (!WxUtils.isWx()) {
            return;
        }
        if(wx){//微信
            Loger.log('展示原生广告', type)
            
            switch(type){
                case CustomAdType.One:
                    this.blnHidenOne = false;
                    if(this.ad_Custom_DanGe){
                        this.ad_Custom_DanGe.show();
                    }
                break
                case CustomAdType.Heng:
                    if(this.ad_Custom_HengXiang){
                        this.ad_Custom_HengXiang.show();
                    }
                break
                case CustomAdType.Shu:
                    this.blnHidenShu = false;
                    if(this.ad_Custom_ShuXiang_R){
                        this.ad_Custom_ShuXiang_R.show();
                    }
                    if(this.ad_Custom_ShuXiang_L){
                        this.ad_Custom_ShuXiang_L.show()
                    }
                break
                case CustomAdType.More:
                    if(this.ad_Custom_JuZhen){
                        this.ad_Custom_JuZhen.show()
                    }
                break
            }
        }
    }
    blnHidenOne:boolean = false;
    blnHidenShu:boolean = false;
    /**
     * 隐藏, 销毁原生广告模板
     */
    hidenCustomAd(type){
        if (!WxUtils.isWx()) {
            return;
        }
        if(wx){//微信
            Loger.log('关闭原生广告',type)
            switch(type){
                case CustomAdType.One:
                    this.blnHidenOne = true;
                    if(this.ad_Custom_DanGe){
                        this.ad_Custom_DanGe.hide();
                    }
                break
                case CustomAdType.Heng:
                    if(this.ad_Custom_HengXiang){
                        this.ad_Custom_HengXiang.hide()
                    }
                break
                case CustomAdType.Shu:
                    this.blnHidenShu = true;
                    if(this.ad_Custom_ShuXiang_R){
                        this.ad_Custom_ShuXiang_R.hide()
                    }
                    if(this.ad_Custom_ShuXiang_L){
                        this.ad_Custom_ShuXiang_L.hide()
                    } 
                break
                case CustomAdType.More:
                    if(this.ad_Custom_JuZhen){
                        this.ad_Custom_JuZhen.hide()
                    }
                break
            }
        }
    }

}